package org.svnadmin.service.svn;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.svnadmin.common.util.PropUtils;
import org.svnadmin.dao.*;
import org.svnadmin.entity.Pj;
import org.svnadmin.entity.PjAuth;
import org.svnadmin.entity.PjGrUsr;
import org.svnadmin.entity.Usr;
import org.svnadmin.service.SimulationService;
import org.svnadmin.util.EncryptUtil;
import org.svnadmin.util.SystemUtil;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * CollabNetSvnService
 *
 * @author hewenjie
 * @data 2021/6/22
 */
@Service(CollabNetSvnService.BEAN_NAME)
public class CollabNetSvnService extends SvnService {

    /**
     * Bean名称
     */
    public static final String BEAN_NAME = "collabNetSvnService";

    /**
     * 分隔符
     */
    private static final String SEP = System.getProperty("line.separator");
    /**
     * 日志
     */
    private final Logger LOG = Logger.getLogger(this.getClass());

    /**
     * 项目DAO
     */
    @Resource(name = PjDao.BEAN_NAME)
    protected PjDao pjDao;

    /**
     * 用户DAO
     */
    @Resource(name = UsrDao.BEAN_NAME)
    protected UsrDao usrDao;

    /**
     * 项目组DAO
     */
    @Resource(name = PjGrDao.BEAN_NAME)
    protected PjGrDao pjGrDao;

    /**
     * 项目组用户DAO
     */
    @Resource(name = PjGrUsrDao.BEAN_NAME)
    protected PjGrUsrDao pjGrUsrDao;

    /**
     * 项目权限DAO
     */
    @Resource(name = PjAuthDao.BEAN_NAME)
    protected PjAuthDao pjAuthDao;

    /**
     * 浏览器仿真模拟器
     */
    @Resource(name = SimulationService.BEAN_NAME)
    protected SimulationService simulationService;

    @PostConstruct
    public void init(){
        init(pjDao,usrDao,pjGrDao,pjGrUsrDao,pjAuthDao,LOG);
    }


    @Override
    void exportPasswdHTTPMutil(File root, List<Usr> usrList) {

    }

    @Override
    void exportPasswdHTTP(Pj pj, List<Usr> usrList) {

    }

    @Override
    void exportPasswdSVN(Pj pj, List<Usr> usrList) {
        System.out.println(pj);
        System.out.println(usrList);
    }

    @Override
    void exportAuthzHTTPMutil(File root, Map<String, List<PjGrUsr>> pjGrUsrMap, Map<String, List<PjAuth>> resMap) {

    }

    @Override
    void exportAuthz(Pj pj, Map<String, List<PjGrUsr>> pjGrUsrMap, Map<String, List<PjAuth>> resMap) {
        if (pj == null || StringUtils.isBlank(pj.getPj())) {
            return;
        }
        /*
         * if(pjGrList == null || pjGrList.size() == 0){ return; } if(pjAuthMap
         * == null || pjAuthMap.size() == 0){ return; }
         */
        File outFile = new File(SystemUtil.home(), "/data/conf/svn_access_file");
        StringBuffer contents = new StringBuffer();
        contents.append("[aliases]").append(SEP);
        contents.append("[groups]").append(SEP);

        for (Iterator<String> grIterator = pjGrUsrMap.keySet().iterator(); grIterator
                .hasNext();) {
            String gr = grIterator.next();
            contents.append(gr).append("=");
            List<PjGrUsr> pjGrUsrList = pjGrUsrMap.get(gr);
            for (int i = 0; i < pjGrUsrList.size(); i++) {
                PjGrUsr pjGrUsr = pjGrUsrList.get(i);
                if (pjGrUsr.getUsr() == null) {
                    continue;
                }
                if (i != 0) {
                    contents.append(",");
                }
                contents.append(pjGrUsr.getUsr());
            }
            contents.append(SEP);
        }

        contents.append(SEP);

        for (Iterator<String> resIterator = resMap.keySet().iterator(); resIterator.hasNext();) {
            String res = resIterator.next();
            contents.append(res).append(SEP);
            for (PjAuth pjAuth : resMap.get(res)) {
                if (StringUtils.isNotBlank(pjAuth.getGr())) {
                    contents.append("@").append(pjAuth.getGr()).append("=")
                            .append(pjAuth.getRw()).append(SEP);
                } else if (StringUtils.isNotBlank(pjAuth.getUsr())) {
                    contents.append(pjAuth.getUsr()).append("=")
                            .append(pjAuth.getRw()).append(SEP);
                }
            }
            contents.append(SEP);
        }

        this.write(outFile, contents.toString());
    }

    @Override
    void exportSvnConf(Pj pj) {

    }

    @Override
    void exportSVNPathConf(Pj pj) {

    }

    @Override
    void exportSVNParentPathConf(File root) {

    }

    @Override
    public List<Usr> getSvnUserList() {
        File file = new File(SystemUtil.home() +File.separator+"data\\conf\\svn_auth_file");
        List<Usr> res = new ArrayList<>();
        try {
            List<String> list = FileUtils.readLines(file,"UTF-8");
            for (String t:list){
                if(t.contains(":")){
                    String[] split = t.split(":");
                    Usr usr = new Usr();
                    usr.setUsr(split[0]);
                    usr.setName(split[0]);
                    usr.setPsw(EncryptUtil.encrypt(PropUtils.get("user.password")));
                    usr.setRole("");
                    res.add(usr);
                }
            }
            return res;
        } catch (IOException e) {
            LOG.error("文件路径不存在：" + file.getPath());
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 添加同步用户信息到SVN
     *
     * @param usr Usr
     * @param state 1 添加，2 删除，3 修改密码
     * return 0 添加用户成功 1 添加用户失败
     *        2 删除用户成功 3 删除用户失败
     *        4 修改密码成功 5 修改密码失败
     */
    @Override
    public int synSvnUseConfig(Usr usr, int state)  {
        if (state == 1) {
            if(simulationService.addUser(usr.getUsr(),usr.getName(),usr.getPsw(),"maxversion@163.com")){
                return 0;
            }else {
                return 1;
            }
        } else if (state == 2) {
            if(simulationService.deleteUser(usr.getUsr())){
                return 2;
            }else {
                return 3;
            }
        }
        if(simulationService.updatePwd(usr.getUsr(),usr.getPsw())){
            return 4;
        }else {
            return 5;
        }
    }
}
